package org.linphone.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.json.JSONTokener;
import org.linphone.LinphoneService;
import com.leehuubsd.yiyanzb.R;
import com.umeng.analytics.MobclickAgent;

import org.linphone.setup.SetupActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ModifyWordActivity extends Activity implements OnClickListener {
	private EditText newpword, newpword1, yz;
	private EditText phone;
	private Button button, btnhq;
	private ImageView imageView;
	private SharedPreferences sharedPreferences;
	private String userName, vCode, newpassword, newword, s, userPwd;
	private Editor edit;
	private String https;
	private LinearLayout ll;
	private RelativeLayout yy;
	private String phones;
	private static final int WIZARD_INTENT = 1;
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_modify);
		super.onCreate(savedInstanceState);
		https = getResources().getString(R.string.http);
		sharedPreferences = getSharedPreferences("zhonghexin",
				Context.MODE_WORLD_READABLE);
		edit = sharedPreferences.edit();

		Intent intent = getIntent();

		phones = intent.getStringExtra("phones");
		time = new TimeCount(60000, 1000);// 构造CountDownTimer对象
		find();
	}

	private void find() {
		// phone, pword, newpword, newpword1, yz
		yy = (RelativeLayout) findViewById(R.id.login_yy);
		phone = (EditText) findViewById(R.id.modify_phone);
		if (!TextUtils.isEmpty(phones)) {
			phone.setText(phones);
		}
		ll = (LinearLayout) findViewById(R.id.login_task_loading);
		newpword = (EditText) findViewById(R.id.modify_newpassword);
		newpword1 = (EditText) findViewById(R.id.modify_newpassword1);
		yz = (EditText) findViewById(R.id.modify_yz);
		imageView = (ImageView) findViewById(R.id.modify_back);
		btnhq = (Button) findViewById(R.id.modify_hq);
		button = (Button) findViewById(R.id.modify);
		btnhq.setOnClickListener(this);
		button.setOnClickListener(this);
		imageView.setOnClickListener(this);
		yy.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.modify:
			String Phone = phone.getText().toString();
			vCode = yz.getText().toString();
			newpassword = newpword.getText().toString();
			newword = newpword1.getText().toString();
			if (newpassword.equals(newword)) {
				ll.setVisibility(View.VISIBLE);
				final StringBuffer path = new StringBuffer(
						https
								+ "/api/vosoem/EditePassword?userName=[手机号]&vCode=[验证码]&newPwd=[密码]&proxyId=[定制]"
										.replace("[手机号]", Phone)
										.replace("[验证码]", vCode)
										.replace("[密码]", newpassword)
										.replace(
												"[定制]",
												getResources().getString(
														R.string.oem)));
				getdate(path.toString(), 1);
			} else {
				Toast.makeText(getApplicationContext(), "新密码不一致！",
						Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.modify_hq:
			btnhq.setClickable(false);
			String Phones = phone.getText().toString();
			if (!TextUtils.isEmpty(Phones)) {
				final StringBuffer path = new StringBuffer(
						getResources().getString(R.string.http)
								+ "/api/Account/GetValidateCode?SrcPhone=[手机号]&proxyId=[定制]&Type=[类型]"
										.replace("[手机号]", Phones)
										.replace(
												"[定制]",
												getResources().getString(
														R.string.oem))
										.replace("[类型]", "2"));
				ll.setVisibility(View.VISIBLE);
				getdate(path.toString(), 2);
			} else {
				mToast("请填写注册手机号");
			}
			break;
		case R.id.modify_back:
			String phones = phone.getText().toString();
			Intent intent = new Intent(LinphoneService.instance(),
					SetupActivity.class);
			startActivityForResult(intent, WIZARD_INTENT);
			finish();
			break;
		case R.id.login_yy:
			btnhq.setClickable(false);
			yy.setClickable(false);
			String Phoness = phone.getText().toString();
			if (!TextUtils.isEmpty(Phoness)) {
				final StringBuffer path = new StringBuffer(
						getResources().getString(R.string.http)
								+ "/api/Account/GetValidateCode?SrcPhone=[手机号]&proxyId=[定制]&Type=[类型]"
										.replace("[手机号]", Phoness)
										.replace(
												"[定制]",
												getResources().getString(
														R.string.oem))
										.replace("[类型]", "2"));
				ll.setVisibility(View.VISIBLE);
				getdate(path.toString(), 2);
			} else {
				mToast("请填写注册手机号");
			}
			break;

		}

	}

	// get请求
	private void getdatep(String path) {
		RequestQueue queue = Volley.newRequestQueue(this);
		String url = path;
		StringRequest request = new StringRequest(Method.GET, url,
				new Listener<String>() {
					@Override
					public void onResponse(String response) {
						parserToObjectp(response);
						ll.setVisibility(View.GONE);
					}
				}, new ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError arg0) {
						Log.i("log", "!!!!onErrorResponse" + arg0.toString());
						Toast.makeText(getApplicationContext(), "网络错误！",
								Toast.LENGTH_SHORT).show();
						ll.setVisibility(View.GONE);
					}
				});
		queue.add(request);
	}

	// get请求
	private void getdate(String path, final int i) {
		RequestQueue queue = Volley.newRequestQueue(this);
		String url = path;
		StringRequest request = new StringRequest(Method.GET, url,
				new Listener<String>() {
					@Override
					public void onResponse(String response) {
						switch (i) {
						case 1:
							parserToObject(response);
							finish();
							break;
						case 2:
							parserToObject1(response);
							break;

						default:
							break;
						}

						ll.setVisibility(View.GONE);
					}
				}, new ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError arg0) {
						Log.i("log", "!!!!onErrorResponse" + arg0.toString());
						Toast.makeText(getApplicationContext(), "网络错误！",
								Toast.LENGTH_SHORT).show();
						ll.setVisibility(View.GONE);
						btnhq.setClickable(true);
						yy.setClickable(true);
					}
				});
		queue.add(request);
	}

	// json解析 08-03 10:41:14.600: I/LOL(2239): {"retCode":0}

	protected void parserToObject(String json) {
		JSONObject object;
		JSONTokener jsonTokener = new JSONTokener(json);
		try {
			JSONObject person = (JSONObject) jsonTokener.nextValue();
			int i = person.getInt("retCode");
			if (i == 0) {
				Toast.makeText(getApplicationContext(), "密码修改成功",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getApplicationContext(),
						person.getString("message"), Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Toast.makeText(getApplicationContext(), "服务器异常！",
					Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
	}

	// json解析
	protected void parserToObject1(String json) {
		JSONObject object;
		JSONTokener jsonTokener = new JSONTokener(json);
		try {
			JSONObject person = (JSONObject) jsonTokener.nextValue();
			boolean i = person.getBoolean("success");
			if (i) {
				Toast.makeText(getApplicationContext(), "获取验证码成功，请稍后！",
						Toast.LENGTH_SHORT).show();
				time.start();// 开始计时
			} else {
				Toast.makeText(getApplicationContext(),
						person.getString("message"), Toast.LENGTH_SHORT).show();
				btnhq.setClickable(true);
				yy.setClickable(true);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Toast.makeText(getApplicationContext(), "服务器异常！",
					Toast.LENGTH_SHORT).show();
			btnhq.setClickable(true);
			yy.setClickable(true);
			e.printStackTrace();
		}
	}

	private TimeCount time;

	/* 定义一个倒计时的内部类 */
	class TimeCount extends CountDownTimer {
		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
		}

		@Override
		public void onFinish() {// 计时完毕时触发
			btnhq.setText("重新获取");
			btnhq.setClickable(true);
			yy.setClickable(true);
		}

		@Override
		public void onTick(long millisUntilFinished) {// 计时过程显示

			btnhq.setText(millisUntilFinished / 1000 + "秒");
		}
	}

	/**
	 * 解析返回内容
	 * 
	 * @author li Jan 15, 2015
	 */
	public void parserToObjectp(String response) {
		JSONTokener jsonTokener = new JSONTokener(response);
		try {
			JSONObject object = (JSONObject) jsonTokener.nextValue();
			if (object.getInt("retCode") == 0) {
				try {
					mToast("密码修改成功");
					edit.clear();
					edit.commit();
					finish();
					Intent intent = new Intent(LinphoneService.instance(),
							SetupActivity.class);
					startActivityForResult(intent, WIZARD_INTENT);
				} catch (Exception e) {
				}
				ll.setVisibility(View.GONE);
			} else {
				mToast(object.getString("exception") + "("
						+ object.getInt("retCode") + ")");
				ll.setVisibility(View.GONE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			mToast("数据异常");
			ll.setVisibility(View.GONE);
		}
	}

	private void mToast(String string) {
		// TODO Auto-generated method stub
		Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT)
				.show();
	}
}
